<template> 
	<view class="container" style="height:100%; display: flex; flex-direction: column;">
		<view class="header" style="maring: 10rpx 10rpx">
			<view class="header-title"> 点击转盘开始摇号。</view>  
			<view class="header-title" style="color: red; font-weight: bold;">请注意：摇号之后不能再退款了！ </view>  
			<!-- <view class="header-title" style="color: red; font-weight: bold;"> 多选1时，请再10秒内提交，否则系统自动随机选择！ </view>  -->
		</view>  
		
		<view class="main" style="flex:1; display: flex; align-items: center; justify-content: center;">   
			<view class="canvas-container">  
				<view :animation="animationData" class="canvas-content" >  
					<view class="canvas-line">  
						<view class="canvas-litem" v-for="(item,index1) in awardsList" :key="index1" :style="[{transform:'rotate('+item.lineTurn+')'}]"></view>  
					</view>  

					<view class="canvas-list">  
						<view class="canvas-item" v-for="(iteml,index2) in awardsList" :key="index2">  
							<view class="canvas-item-text" :style="[{transform:'rotate('+iteml.turn+')'}]">  
								<text :style='"font-size:"+fontSize+"rpx"'>{{iteml.award}}</text>  
							</view>  
						</view>  
					</view>  
				</view>  

				<view @tap="onTapStart" class="canvas-btn" v-bind:class="btnDisabled">开始    </view>  
			</view>  
		</view>
		<view style="width: 100%; height: 100rpx;"></view>

		<!-- 抽签模态窗口 -->
		<view class="cu-modal"  :class="showModal?'show':''">
			<view class="cu-dialog pd-lg">
				<view>
					<view class="title lay-c-c pd-xxl"><text>摇{{lotteryNumber}}选1</text></view>
					<!-- <view class="header-title">{{discount}}秒后系统将自动分配</view>  -->
					<radio-group @change="onSelectSeatChange($event)" class="lay-sb-c-c">
						<!-- 最多支持摇5选1 -->
						<view v-for="(item, index) in lotteryMultiResults" :key="index" class="pd-h-sm">
							<label class="radio">
								<radio :value='item.id' :checked="item.id==selectSeatId" />
								{{item.seat_no}}号
							</label>
						</view>
					</radio-group>
		
					<view class="lay-c-c pd-xxl">
						<button class="btn bk-blue white" style="width: 30%;" @click="onTapSubmit">提交</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>  
import {MyTip} from '../../components/ssty/common.js';
	import {
		getSeatsForLottery,
		doLottery,
		bindSeatToOrderV2,
		changeSeat_bind
	} from '@/api/fsh.js';
	const app = getApp();
	
    export default {  
		data() {  
			let awards = []
			//for(let i = 0; i < 40; i++) {
			//	awards.push({ index: i, name: (i+1), type:0})  
			//}
            return {  
				fontSize: awards.length<50?30:(awards.length<70?20:15),
                awardsConfig : {  
                                chance: true,  
                                awards: awards 
                            },  
                awardsList: {},  
				awardsIndex: 0,
                animationData: {},  
                btnDisabled: '',
				lotteryNumber: 1,
				discount: 10,
				lotteryMultiResults: [{
					seat_no: '',
				}],
				selectSeatId: 0,
				showModal: false,
				timer: null
            };  
        },  
		onBackPress(options) {
		    return showModal;
		},
        onLoad:function(options){  
            uni.setNavigationBarColor({  
                    frontColor: '#ffffff',  
                    backgroundColor: '#fc4141',  
                    animation: {  
                            duration: 400,  
                            timingFunc: 'easeIn'  
                    }  
            })  
			
			console.log("lotterySeat::onLoad| options=%o", options);
			
			this.isChangeSeat = options.isChangeSeat;
			this.ypOdId = options.ypOdId;
			this.loadSeats(this.ypOdId);
        }, 
		onShow() {
			let that = this
			// if(app.globalData.lotteryTime>0){
			// 	if(app.globalData.lotteryTime - Date.now() > 0){
			// 		clearInterval(that.timer)
			// 		that.timer = setInterval(()=>{
			// 			that.discount = Math.ceil((app.globalData.lotteryTime - Date.now())/1000)
			// 			if(that.discount<=0){
			// 				clearInterval(that.timer)
			// 				app.globalData.lotteryTime = 0;
			// 				that.btnDisabled= '';
			// 				app.globalData.fshingPageYpOdId = that.ypOdId;
			// 				uni.switchTab({
			// 					url: '/pages/fsh_main/fishing'
			// 				});
			// 			}
			// 		},1000)
			// 	}else{
			// 		app.globalData.lotteryTime = 0;
			// 		clearInterval(that.timer)
			// 	}
			// }
		},
        onReady: function (e) { 
                this.drawAwardRoundel();  

                //分享  
                uni.showShareMenu({  
                    withShareTicket: true  
                }); 
        },  
        methods: { 
			loadSeats(ypOdId) {
				uni.showLoading({
					title: '正在加载中...'
				});
				getSeatsForLottery(ypOdId).then(res => {
					uni.hideLoading();
					let seats = res.entity.seats;
					//this.awardIndex = seats.findIndex(a=>a.id == res.entity.randomSeatId);
					this.awardsConfig.awards = seats.map((item,index)=>({'index': index, 'name':item.seat_no, 'type':0}));
					this.fontSize = seats.length<50?30:(seats.length<70?20:15);
					this.awardsList = [];
					
					this.lotteryNumber = res.entity.lotteryNumber;

					this.$nextTick(() => this.drawAwardRoundel());
				}).catch(err => {
					uni.hideLoading();
					console.log("loadSeats fail ", err);
					
					uni.showModal({
						content: err.msg,
						showCancel: false,
						complete:()=>{
							app.globalData.fshingPageYpOdId = this.ypOdId;
							uni.switchTab({
								url: '/pages/fsh_main/fishing'
							});
						}
					})
				});
			},
			
                  //画抽奖圆盘  
            drawAwardRoundel: function () {  
                    var awards = this.awardsConfig.awards;  
                    var awardsList = [];  
                    var turnNum = 1 / awards.length*360;  // 文字旋转 turn 值  

                    // 奖项列表  
                    for (var i = 0; i < awards.length; i++) {  
                      awardsList.push({ turn: i * turnNum + 'deg', lineTurn: i * turnNum + turnNum / 2 + 'deg', award: awards[i].name });  
                    }  

                    this.btnDisabled = this.awardsConfig.chance ? '' : 'disabled';  
                    this.awardsList = awardsList;  
          },  

			onTapStart() {
				// 先请求后台，拿到结果，好确定最终滚动的位置
				doLottery(this.ypOdId,this.isChangeSeat).then(res => { // lottery.js od_lottery
					this.lotteryMultiResults = res.entity.seats;
					this.selectSeatId = res.entity.seats[0].id;
					console.log("doLottery, selectSeatId="+this.selectSeatId,this.isChangeSeat);
					this.awardIndex = this.awardsConfig.awards.findIndex(a=>a.name == res.entity.seats[0].seat_no);
					this.playReward();
				}).catch(err => {
					console.log("doLottery fail:", err);
					this.$nextTick(() => {
						uni.showModal({
							content: err.msg,
							showCancel: false,
							complete: () => {}
						})
					})
				})
			},
                  //发起抽奖  
            playReward: function () {  
                    //中奖index  
                    var awardsNum = this.awardsConfig.awards;  
                    //var awardIndex = Math.round(Math.random()*(awardsNum.length-1));//随机数  
					var awardIndex = this.awardIndex;  
                    var runNum = 8;//旋转8周  
                    var duration = 4000;//时长  

                    // 旋转角度  
                    this.runDeg = this.runDeg || 0;  
                    this.runDeg = this.runDeg + (360 - this.runDeg % 360) + (360 * runNum - awardIndex * (360 / awardsNum.length))  
                    //创建动画  
                    var animationRun = uni.createAnimation({  
                      duration: duration,  
                      timingFunction: 'ease'  
                    })  
                    animationRun.rotate(this.runDeg).step();  
                    this.animationData= animationRun.export();  
                    this.btnDisabled= 'disabled';  

                    // 中奖提示  
                    var awardsConfig = this.awardsConfig;  
                    // var awardType = awardsConfig.awards[awardIndex].type;     
                    // if (awardType == 0) {  
                        setTimeout(function () {  
							let that = this;
							if(this.lotteryNumber == 1) {
								if (this.isChangeSeat) {
									changeSeat_bind(this.ypOdId, this.selectSeatId).then(res => {
										uni.hideLoading();
										app.globalData.fshingPageYpOdId = that.ypOdId;
										uni.switchTab({
											url: '/pages/fsh_main/fishing'
										});
									}).catch(err => {
										console.log("onTapBtn fail:", err);
										uni.hideLoading();
										uni.showModal({
											title: '摇号失败，请重新摇，'+err.msg,  
											content: err.msg, 
											showCancel: false,
											success: function () {
												that.loadSeats(that.ypOdId);
											},
										})
									});
								} else {
									bindSeatToOrderV2(this.ypOdId, this.selectSeatId).then(res => {
										uni.hideLoading();
										uni.showModal({
											title: '恭喜',  
											content: '摇到' + (awardsConfig.awards[awardIndex].name + '号') ,  
											showCancel: false,
											success: function (res) {
												that.btnDisabled= '';
												app.globalData.fshingPageYpOdId = that.ypOdId;
												uni.switchTab({
													url: '/pages/fsh_main/fishing'
												});
											}
										});
									}).catch(err => {
										console.log("onTapBtn fail:", err);
										uni.hideLoading();
										uni.showModal({
											title: '摇号失败，请重新摇，'+err.msg,  
											content: err.msg, 
											showCancel: false,
											success: function () {
												that.loadSeats(that.ypOdId);
											},
										})
									});
								}
								// bindSeatToOrderV2(that.ypOdId, that.selectSeatId).then(res => {
								// 	uni.hideLoading();
								// 	uni.showModal({
								// 		title: '恭喜',  
								// 		content: '摇到' + (awardsConfig.awards[awardIndex].name + '号') ,  
								// 		showCancel: false,
								// 		success: function (res) {
								// 			that.btnDisabled= '';
								// 			app.globalData.fshingPageYpOdId = that.ypOdId;
								// 			uni.switchTab({
								// 				url: '/pages/fsh_main/fishing'
								// 			});
								// 		}
								// 	});
								// }).catch(err => {
								// 	console.log("onTapBtn fail:", err);
								// 	uni.hideLoading();
								// 	uni.showModal({
								// 		title: '摇号失败，请重新摇，'+err.msg,  
								// 		content: err.msg, 
								// 		showCancel: false,
								// 		success: function () {
								// 			that.loadSeats(that.ypOdId);
								// 		},
								// 	})
								// });
							}
							else {
								// 摇N先1
								let that = this;
								this.showModal = true;
								// if(app.globalData.lotteryTime>0){
									
								// }else{
								// 	app.globalData.lotteryTime = Date.now() + 10000;
								// }
								// clearInterval(that.timer)
								// that.timer = setInterval(()=>{
								// 	that.discount = Math.ceil((app.globalData.lotteryTime - Date.now())/1000)
								// 	if(that.discount<=0){
								// 		clearInterval(that.timer)
								// 		app.globalData.lotteryTime = 0;
								// 		that.btnDisabled= '';
								// 		app.globalData.fshingPageYpOdId = that.ypOdId;
								// 		uni.switchTab({
								// 			url: '/pages/fsh_main/fishing'
								// 		});
								// 	}
								// },1000)
							}
                        }.bind(this), duration);  
                    // }else{  
                    //     setTimeout(function () {  
                    //         uni.showModal({  
                    //             title: '很遗憾',  
                    //             content: '没中奖 ' + (awardsConfig.awards[awardIndex].name),  
                    //             showCancel: false  
                    //         });  
                    //         this.btnDisabled= '';  
                    //     }.bind(this), duration);  
                    // }  

            } ,
			 
			 onSelectSeatChange(e) {
			 	this.selectSeatId = parseInt(e.detail.value);
			 	console.log("select seat id=" + this.selectSeatId);
			 },
			 
			 onTapSubmit() {
				 let that = this;
				 if (this.isChangeSeat) {
				 	changeSeat_bind(this.ypOdId, this.selectSeatId).then(res => {
				 		uni.hideLoading();
						that.btnDisabled= '';
				 		app.globalData.fshingPageYpOdId = that.ypOdId;
				 		uni.switchTab({
				 			url: '/pages/fsh_main/fishing'
				 		});
				 	}).catch(err => {
				 		console.log("onTapBtn fail:", err);
				 		uni.hideLoading();
				 		uni.showModal({
				 			title: '提交失败',  
				 			content: err.msg, 
				 			showCancel: false
				 		})
				 	});
				 } else {
				 	bindSeatToOrderV2(this.ypOdId, this.selectSeatId).then(res => {
						uni.hideLoading();
				 		uni.showModal({
				 			title: '提交成功', 
				 			showCancel: false,
				 			success: function (res) {
				 				that.btnDisabled= '';
				 				app.globalData.fshingPageYpOdId = that.ypOdId;
				 				uni.switchTab({
				 					url: '/pages/fsh_main/fishing'
				 				});
				 			}
				 		});
				 	}).catch(err => {
				 		console.log("onTapBtn fail:", err);
				 		uni.hideLoading();
				 		uni.showModal({
				 			title: '提交失败',  
				 			content: err.msg, 
				 			showCancel: false
				 		})
				 	});
				 }
				 // bindSeatToOrderV2(that.ypOdId, that.selectSeatId).then(res => {
				 // 	uni.hideLoading();
				 // 	uni.showModal({
				 // 		title: '提交成功', 
				 // 		showCancel: false,
				 // 		success: function (res) {
				 // 			that.btnDisabled= '';
				 // 			app.globalData.fshingPageYpOdId = that.ypOdId;
				 // 			uni.switchTab({
				 // 				url: '/pages/fsh_main/fishing'
				 // 			});
				 // 		}
				 // 	});
				 // }).catch(err => {
				 // 	console.log("onTapBtn fail:", err);
				 // 	uni.hideLoading();
				 // 	uni.showModal({
				 // 		title: '提交失败',  
				 // 		content: err.msg, 
				 // 		showCancel: false
				 // 	})
				 // });
			 }
        }  

    }  
</script>

<style lang="scss" scoped>
	
	@import "@/leui.scss";
	
	page {
		height: 100%;
		background-color: #F1F1F1;
	}
	
.header{  
    display: flex;  
    flex-direction: column;  
    align-items: center;  
    justify-content: flex-start;  
    height: 200rpx;
}  
/* 转盘 */  
.canvas-container {  
  margin: 0 auto;  
  position: relative;  
  width: 700upx;  
  height: 700upx;  
  border-radius: 50%;  
  box-shadow: 0 10upx 30upx #333, 0 0 10upx #000;  
    border: 10rpx solid #fc4141;  
}  
.canvas-content {  
  position: absolute;  
  left: 0;  
  top: 0;  
  z-index: 1;  
  display: block;  
  width: 700upx;  
  height:700upx;  
  border-radius: inherit;  
  background-clip: padding-box;  
  /* background-color: #ffcb3f; */  
}  
.canvas-element {  
  position: relative;  
  z-index: 1;  
  width: inherit;  
  height: inherit;  
  border-radius: 50%;  
}  
.canvas-list {  
  position: absolute;  
  left: 0;  
  top: 0;  
  width: inherit;  
  height: inherit;  
  z-index: 9999;  
}  
.canvas-item {  
  position: absolute;  
  left: 0;  
  top: 0;  
  width: 100%;  
  height: 100%;  
  color: #e4370e;  
  font-weight: bold;  
  text-shadow: 0 1upx 1upx rgba(255, 255, 255, 0.6);  
}  
.canvas-item-text {  
  position: relative;  
  display: block;  
  padding-top: 20upx;  
  margin: 0 auto;  
  text-align: center;  
  -webkit-transform-origin: 50% 350upx;  
  transform-origin: 50% 350upx;  
    display: flex;  
    flex-direction: column;  
    align-items: center;  
}  
/* .canvas-item-text text{  
    font-size:30upx;  
}  */
.canvas-item-text-img{  
    width:60upx;  
    height:60upx;  
    padding-top:10upx;  
}  

/* 分隔线 */  
.canvas-line {  
  position: absolute;  
  left: 0;  
  top: 0;  
  width: inherit;  
  height: inherit;  
  z-index: 99;  
}  
.canvas-litem {  
  position: absolute;  
  left: 350upx;  
  top: 0;  
  width: 3upx;  
  height: 350upx;  
  background-color: rgba(228, 55, 14, 0.1);  
  overflow: hidden;  
  -webkit-transform-origin: 50% 350upx;  
  transform-origin: 50% 350upx;  
}  

/**  
* 抽奖按钮  
*/  
.canvas-btn {  
  position: absolute;  
  left: 310upx;  
  top: 310upx;  
  z-index: 400;  
  width: 80upx;  
  height: 80upx;  
  border-radius: 50%;  
  color: #f4e9cc;  
  background-color: #e44025;  
  line-height: 80upx;  
  text-align: center;  
  font-size: 26upx;  
  text-shadow: 0 -1px 1px rgba(0, 0, 0, 0.6);  
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.6);  
  text-decoration: none;  
}  
.canvas-btn::after {  
  position: absolute;  
  display: block;  
  content: ' ';  
  left: 12upx;  
  top: -44upx;  
  width: 0;  
  height: 0;  
  overflow: hidden;  
  border-width:30upx;  
  border-style: solid;  
  border-color: transparent;  
  border-bottom-color: #e44025;  
}  
.canvas-btn.disabled {  
  pointer-events: none;  
  background: #b07a7b;  
  color: #ccc;  
}  
.canvas-btn.disabled::after {  
  border-bottom-color: #b07a7b;  
}  
.canvas-btn-table{  
    color:#fc4141;  
    width:120upx;  
    text-align: center;  
    position: absolute;  
    left: 240upx;  
    top:360upx;  
    font-size:26upx;  
    background-color: #FFFFFF;  
    opacity: 0.9;  
}  

</style>
